<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Services\social\ten\Qc;
use FreeAbrams\FuncTools;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Validation\ValidationException;

class LoginController extends Controller
{
	use AuthenticatesUsers;
	
	public function home(Request $request)
	{
		$chatUser = '';
		$list = '';
		$messageList = '';
		if (Auth::check() && $request->user()->chatUser) {
			$key = config('api');
			$token = new FuncTools\AccessToken\Token($key['publicKey'], $key['signKey']);
			$chatUser = $token->encrypt($request->user()->chatUser->toArray());
		} elseif (Auth::check() && !$request->user()->chatUser) {
			$chatUser = $request->user()->chatUser()->create();
			if (!$chatUser) {
				return redirect(route('home'));
			}
			$key = config('api');
			$token = new FuncTools\AccessToken\Token($key['publicKey'], $key['signKey']);
			$chatUser = $token->encrypt($chatUser->toArray());
		}
		
		if (env('APP_DEBUG')) {
			$chatUser = 'NVr1vHkTpWR/eMQJ8LAlmbp3bjE4vauPKtRA9mqQ66riAY9xYlAjNwyHkZHGLR3W/uHSBGMM4tn+BttNblBaAB1XH3V8RdzfcO3zSxZyl+l4hEOuwzLhwrwK/PgHJkhtA+DSZtoNyJ8AmF26QJxKBDLY1BPwoKO2QljpaRaAi3Y6PsPJWNX1XeWIdPLKzoIj8ZaHTiEYUovW6aJgjGfll8bJaYXiyAZDI9do3QiJsKuabMsXc58Wacb2WOibbA/1n65ZfAUR+d6jAaUC9FYFV/G1jJqnkG0eU8VQTKhY2e8YSdFKZ4gUR/xbevuKQvdZuhX/wjBaFvdqyQulCL3sig==';
		}
		
		return view('home', compact('chatUser', 'list', 'messageList'));
	}
	
    public function showLoginFrom()
    {
        return view('auth.login');
    }
    
    public function login(Request $request)
    {
//    	?code=340EF153D3A507B0C2F314A1E944C61B&state=f7565ff5868004a2415c3215fb659042
        $validate = Validator::make($request->all(), [
        	'email' => 'required|string',
	        'password' => 'required|string',
        ]);
        
        if ($validate->fails()) {
        	throw ValidationException::withMessages($validate->errors()->toArray());
        }

        $auth = Auth::guard('web')->attempt($request->all(['email', 'password']),
	        $request->all(['remember']));
        
        if (!$auth) {
            throw ValidationException::withMessages([
            	'email' => [trans('auth.failed')]
            ]);
        }
        Session::flash('success', trans('auth.Login Success'));
        return redirect(route('home'));
    }
    
    public function showRegisterFrom()
    {
        return view('auth.register');
    }
    
    public function register(Request $request)
    {
    	$validate = Validator::make($request->all(), [
    		'name' => 'required|string|max:20',
		    'email' => 'required|email|unique:users',
		    'password' => 'required|confirmed|min:6',
		    'password_confirmation' => 'required',
	    ]);
    	if ($validate->fails()) {
    	    throw ValidationException::withMessages($validate->errors()->toArray());
	    }
    	$user = new User();
    	$request->offsetSet('password', Hash::make($request->password));
    	$user->fill($request->all());
    	if (!$user->save()) {
    		Session::flash('danger', '注册失败!');
    	    return back()->withInput();
	    }
    	Auth::guard('web')->login($user);
    	return redirect(route('home'));
    }
    
    public function socialLogin(Request $request)
    {
    	$qc = new Qc();
    	if ($request->code) {
    		$access_token = $qc->get_access_token($request);
    		$openId = $qc->get_openid($access_token);
    		$data = $qc->get_user_info([
    			'oauth_consumer_key' => $qc->config['APP_ID'],
    			'access_token' => $access_token,
    			'openid' => $openId
		    ]);
    		$data['avatar'] = $data['figureurl_qq_1'];
    		$data['openid'] = $openId;
    		$data['name'] = $data['nickname'];
    		$data['status'] = 1;
    		$data['password'] = Hash::make('password');
    		
    		$user = User::query()->firstOrCreate(['openid' => $openId], $data);
    		if ($user) {
    			Session::flash('success', trans('auth.Login Success'));
    			Auth::guard('web')->login($user, true);
    		    return redirect(route('home'));
		    } else {
    			Session::flash('error', '授权失败请稍后重试');
    			redirect(route('home'));
		    }
	    } else {
    	    return redirect($qc->qq_login());
	    }
    }
}
